import { useAppSelector } from '@/store';
import {
  AddChannelAction,
  DelChannelAction,
  GetAllChannelAction,
  GetuserChannelAction,
  SetChannel_idAction,
} from '@/store/action/channel';
import { Popup, Tabs, Toast } from 'antd-mobile';
import { useEffect, useState } from 'react';
import { useDispatch } from 'react-redux';
import Icon from '../Icon';
import styles from './index.module.scss';
import { differenceBy } from 'lodash';
import { ChannelListType } from '@/store/reducer/channel';
import { useHistory } from 'react-router-dom';
export default function Channel() {
  const history = useHistory();
  const dispatch = useDispatch();
  const [BtnState, setBtnState] = useState(false);
  const [visible, setVisible] = useState(false);
  // const [TabKey, setTabKey] = useState('0');
  const { AllchannelList, userChannelList, channel_id } = useAppSelector(
    (state) => state.channel
  );
  useEffect(() => {
    dispatch(GetAllChannelAction());
    dispatch(GetuserChannelAction());
  }, [dispatch]);

  /** 计算剩余推荐频道 */
  // const RestChannelList = AllchannelList.filter((item) => userChannelList.findIndex((val) => val.id === item.id) === -1; });
  const RestChannelList = differenceBy(AllchannelList, userChannelList, 'id');

  /** 编辑用户相关频道记录事件 */
  const handleChangeChannel = async (id: number) => {
    if (userChannelList.length <= 5) return Toast.show('至少保留5个频道哦');
    if (id === 0) return Toast.show('不可以删除推荐频道!');
    await dispatch(DelChannelAction(id));
    if (String(id) === channel_id) {
      dispatch(
        SetChannel_idAction(
          String(
            userChannelList[
              userChannelList.findIndex((val) => val.id === id) - 1
            ].id
          )
        )
      );
    }

    Toast.show('删除频道成功');
  };

  /** 点击频道触发事件 */
  const handleClickChannel = async (id: string = channel_id) => {
    dispatch(SetChannel_idAction(id));
    setVisible(false);
    setBtnState(false);
  };

  /** 添加频道 */
  const handleAddChannel = async (item: ChannelListType) => {
    await dispatch(AddChannelAction(item));
    Toast.show('更新频道成功');
  };

  return (
    <div className={styles.root}>
      <Tabs
        onChange={(key) => dispatch(SetChannel_idAction(key))}
        activeKey={channel_id}
        defaultActiveKey={channel_id}
        className="tabs"
      >
        {userChannelList.map((item) => (
          <Tabs.Tab title={item.name} key={item.id} />
        ))}
      </Tabs>

      <div className="right">
        <Icon type="iconbtn_search" onClick={() => history.push('/search')} />
        <Icon type="iconbtn_channel" onClick={() => setVisible(true)} />
      </div>
      <Popup
        visible={visible}
        onMaskClick={() => handleClickChannel()}
        position="left"
        bodyClassName={styles.channelPopup}
      >
        {/* 顶部栏：带关闭按钮 */}
        <div className="channel-header">
          <Icon
            type="iconbtn_channel_close"
            onClick={() => handleClickChannel()}
          />
        </div>

        {/* 频道列表 */}
        <div className="channel-content">
          {/* 当前已选择的频道列表 */}
          <div className="channel-item edit">
            <div className="channel-item-header">
              <span className="channel-item-title">我的频道</span>
              <span className="channel-item-title-extra">点击进入频道</span>
              <span
                className="channel-item-edit"
                style={{
                  color: BtnState === false ? '#fc6627' : '#fff',
                  backgroundColor: BtnState === false ? '#fff' : '#fc6627',
                }}
                onClick={() => setBtnState(!BtnState)}
              >
                {BtnState === false ? '编辑' : '完成'}
              </span>
            </div>

            <div className="channel-list">
              {userChannelList.map((item) => {
                return (
                  <div key={item.id} className="channel-list-item">
                    {BtnState === true && (
                      <Icon
                        type="iconbtn_tag_close"
                        onClick={() => handleChangeChannel(item.id)}
                      />
                    )}
                    <span
                      style={{
                        color: Number(channel_id) === item.id ? '#fc6627' : '',
                      }}
                      onClick={() => handleClickChannel(String(item.id))}
                    >
                      {item.name}
                    </span>
                  </div>
                );
              })}
            </div>
          </div>

          {/* 推荐的频道列表 */}
          <div className="channel-item">
            <div className="channel-item-header">
              <span className="channel-item-title">频道推荐</span>
              <span className="channel-item-title-extra">点击添加频道</span>
            </div>
            <div className="channel-list">
              {RestChannelList.map((item) => (
                <span
                  className="channel-list-item"
                  key={item.id}
                  onClick={() => handleAddChannel(item)}
                >
                  + {item.name}
                </span>
              ))}
            </div>
          </div>
        </div>
      </Popup>
    </div>
  );
}
